# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from utils.log_util import LoggerUtil
from utils.Constants import *

log = LoggerUtil.get_logger(__name__)

# Email发送邮件参数配置
email_user = email_user
email_pass = email_pass
email_sender = email_sender
email_server = email_server

def send_mail(recivers, sub, content, filespath):
    try:
        user = email_sender + "<" + email_user + ">"
        # 创建一个带附件的实例
        message = MIMEMultipart()
        message['Subject'] = sub
        message['From'] = user
        message['To'] = ";".join(recivers)

        # 邮件正文内容
        message.attach(MIMEText(content, 'plain', 'utf-8'))

        for file in filespath:
            att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', file.split('/')[len(file.split('/'))-1]))
            # att["Content-Disposition"] = 'attachment; filename="%s"' % (file.split('/')[len(file.split('/'))-1])
            message.attach(att)

        server = smtplib.SMTP_SSL(email_server, 465)
        server.connect(email_server, 465)  # 启用SSL发信, 端口一般是465
        server.login(email_user, email_pass)
        server.sendmail(user, recivers, message.as_string())
        server.close()
        log.info("---Email_SEND_SUCCESSED--- 邮件发送成功 ---Email_SEND_SUCCESSED---")
    except Exception as e:
        log.error("---Email_Error--- 发送邮件出错！ ---Email_Error---")
        log.exception(e)